# Take a calendar and assigns users to shifts
#
#

import webapp2
from google.appengine.ext import db

import ext
			
	
class MainPage(ext.SlotHandler):
	def get(self):
		ext.clearDb()
		
		ext.createTestCalOpen()
		
		cal = ext.Calendar.all().get();

		self.printCal(cal)
		
		cal2 = ext.clone_entity(cal);
		cal2.put()
		
		# Find shift with fewest people signed up
		shk_sp = ext.Shift.get(cal2.shifts[0])
		lshk = len(shk_sp.availAccounts)

		for shk in cal2.shifts:
			shk = ext.clone_entity(ext.Shift.get(shk)).key()
			shk.put()
		
		# get the shift with the fewest people available
		for shk in cal2.shifts:
			sh = ext.Shift.get(shk)
			if len(sh.availAccounts) < lshk:
				lshk = len(sh.availAccounts)
				shk_sp = shk

			# get the person to assign
			pk_best = ext.Shift.get(shk_sp).accounts[0].key()
			for pk in ext.Shift.get(shk_sp).accounts:
				#  first criteria is fewest availabilities
				if len(ext.Account.get(pk).shifts) < len(ext.Account.get(pk_best).shifts):
					# first tie-breaker is fewer assigned shifts
					if len(ext.Account.get(pk).assigned) <= len(ext.Account.get(pk_best).assigned):
						pk_best = pk
			sh_real = ext.Shift.gql("WHERE cal = :1 AND day = :2 AND time = :3", cal.key(), ext.Shift.get(shk_sp).day, ext.Shift.get(shk_sp).time).get() 
			ext.addAssign(ext.Account.get(pk_best), sh_real)
			ext.delShift(ext.Shift.get(shk_sp), cal2)
		cal.closed = True;
		cal2.delete()
		
		
app = webapp2.WSGIApplication([('/makeCal', MainPage)],
                              debug=True)